package com.wedo.mall.activity.user;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.e.library.activity.EActivity;
import com.e.library.http.EClient;
import com.e.library.utils.ESPUtils;
import com.hyphenate.chat.EMClient;
import com.wedo.mall.R;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.dialog.ShareDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

public class SettingActivity extends EActivity {

    public static final String USER = "user";
    public static final String USERNAME = "username";
    public static final String PASSWORD = "password";

    private WLogin wLogin;

    @BindView(R.id.sw_location) Switch sw_location;
    @BindView(R.id.tv_cache) TextView tv_cache;
    @BindView(R.id.rl_clearcache) RelativeLayout rl_clearcache;
    @BindView(R.id.rl_location) RelativeLayout rl_location;

    @Override
    protected int layout() {
        return R.layout.activity_setting;
    }

    @Override
    protected void onActivityCreated(Bundle state) {
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isOPen(this)){
            sw_location.setChecked(true);
        }else{
            sw_location.setChecked(false);
        }

        sw_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b) {
                    //选中时 do some thing

                } else {
                    //非选中时 do some thing
                }
            }
        });
    }

    private void init(){

        try {
            tv_cache.setText(getTotalCacheSize(this));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else {
            copyLogo2SDcard();
        }

    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 监听GPS 跳转到定位服务页面
     */
    private void initGPS() {
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
/*            Toast.makeText(SettingActivity.this, "请打开GPS",
                    Toast.LENGTH_SHORT).show();*/
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage(R.string.user_opengps);
            dialog.setPositiveButton(getResources().getString(R.string.ensure),
                    new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            dialog.setNeutralButton(getResources().getString(R.string.cancel), new android.content.DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            } );
            dialog.show();
        } else {
            // 弹出Toast
//          Toast.makeText(TrainDetailsActivity.this, "GPS is ready",
//                  Toast.LENGTH_LONG).show();
//          // 弹出对话框
//          new AlertDialog.Builder(this).setMessage("GPS is ready")
//                  .setPositiveButton("OK", null).show();
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage(R.string.user_closegps);
            dialog.setPositiveButton(getResources().getString(R.string.ensure),
                    new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            dialog.setNeutralButton(getResources().getString(R.string.cancel), new android.content.DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            } );
            dialog.show();
        }
    }

    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取缓存大小
     * @param context
     * @return
     * @throws Exception
     */
    public static String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    // 获取文件大小
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "Byte";
            return "0K";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    /**
     * 清除缓存
     * @param context
     */
    public void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            boolean i = deleteDir(context.getExternalCacheDir());
            if(i){
                toast(R.string.user_clear_cache_successful);
                tv_cache.setText("0K");
            }else{

            }
        }
    }

    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    @OnClick(R.id.btn_logout)
    protected void onLogoutClick(){
        //activity().toActivity(MessageActivity.class);
        ESPUtils.setString(this,USERNAME,null);
        ESPUtils.setString(this,PASSWORD,null);
        ESPUtils.setString(this,USER,null);
        EClient.with().clearSession(this);
        EMClient.getInstance().logout(false);
        defaultFinish();
    }

    @OnClick(R.id.rl_score)
    protected void onScoreClick() {
        final String packageName = getPackageName();
        try {
            Intent intent =getPackageManager().getLaunchIntentForPackage("com.android.vending");
            ComponentName comp = new ComponentName("com.android.vending",
                    "com.google.android.finsky.activities.LaunchUrlHandlerActivity");
            intent.setComponent(comp);
            intent.setData(Uri.parse("market://details?id=" + packageName));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (android.content.ActivityNotFoundException e) {
            e.printStackTrace();
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
        }
    }

    @OnClick(R.id.rl_feedback)
    protected void onFeedbackClick(){
        toActivity(FeedbackActivity.class);
    }

    @OnClick(R.id.rl_clearcache)
    protected void onClearAllCacheClick(){
        clearAllCache(this);
    }

    @OnClick(R.id.rl_aboutus)
    protected void onAboutUsClick(){
        toActivity(AboutUsActivity.class);
    }

    @OnClick(R.id.rl_agreement)
    protected void onUserAgreementClick(){
        toActivity(UserAgreementActivity.class);
    }

    @OnClick(R.id.rl_language)
    protected void onLanguageClick(){
        toActivity(LanguageActivity.class);
    }

    @OnClick(R.id.rl_share)
    protected void onShareClick(){
        ShareDialog.with(this).app().show();
    }

    @OnClick(R.id.rl_location)
    protected void onLocationClick(){
        initGPS();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1){
            if (grantResults.length >0){
                copyLogo2SDcard();
            }
        }
    }

    private void copyLogo2SDcard() {

        try {
            File dir = new File("/sdcard/com.wedo.mall/");
            if (!dir.exists()){
                dir.mkdirs();
            }

            File file = new File(ShareDialog.SHARE_LOGO);
            if (file.exists()){
                return;
            }
            InputStream myInput;
            OutputStream myOutput = new FileOutputStream(file);
            myInput = this.getAssets().open("ic_logo.png");
            byte[] buffer = new byte[1024];
            int length = myInput.read(buffer);
            while (length > 0) {
                myOutput.write(buffer, 0, length);
                length = myInput.read(buffer);
            }

            myOutput.flush();
            myInput.close();
            myOutput.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

    }


}
